// 用户反馈路由

const express = require('express');
const router = express.Router();
const { logger } = require('../../../config/monitoring');
const { grayReleaseManager } = require('../middleware/grayRelease');

// 反馈类型枚举
const FeedbackType = {
  BUG: 'bug',
  SUGGESTION: 'suggestion',
  COMPLAINT: 'complaint',
  PRAISE: 'praise',
  FEATURE_REQUEST: 'feature_request'
};

// 反馈状态枚举
const FeedbackStatus = {
  PENDING: 'pending',
  PROCESSING: 'processing',
  RESOLVED: 'resolved',
  CLOSED: 'closed'
};

// 提交反馈
router.post('/', async (req, res) => {
  try {
    const userId = req.user?.id;
    const {
      type,
      title,
      content,
      rating,
      screenshots,
      deviceInfo,
      version
    } = req.body;

    // 参数验证
    if (!userId) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户未登录'
      });
    }

    if (!type || !title || !content) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '缺少必要参数'
      });
    }

    if (!Object.values(FeedbackType).includes(type)) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '无效的反馈类型'
      });
    }

    // 创建反馈记录
    const feedbackData = {
      userId,
      type,
      title,
      content,
      rating: rating || null,
      screenshots: screenshots || [],
      deviceInfo: deviceInfo || {},
      version: version || '1.0.0',
      status: FeedbackStatus.PENDING,
      isGrayUser: req.grayRelease.isGrayUser(userId, req.user),
      ip: req.ip,
      userAgent: req.get('User-Agent'),
      createdAt: new Date()
    };

    // 保存到数据库
    // const feedback = await Feedback.create(feedbackData);

    // 记录用户行为
    await req.grayRelease.recordBehavior(userId, 'feedback_submit', {
      feedbackType: type,
      rating
    });

    // 如果是严重问题，立即通知
    if (type === FeedbackType.BUG || type === FeedbackType.COMPLAINT) {
      await notifyAdmins(feedbackData);
    }

    logger.info('Feedback submitted', { userId, type, title });

    res.json({
      success: true,
      code: 200,
      message: '反馈提交成功',
      data: {
        id: Date.now(), // 临时ID，实际应该是数据库生成的ID
        status: FeedbackStatus.PENDING
      }
    });

  } catch (error) {
    logger.error('Failed to submit feedback:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '提交反馈失败'
    });
  }
});

// 获取用户反馈列表
router.get('/my', async (req, res) => {
  try {
    const userId = req.user?.id;
    const { page = 1, limit = 10, type, status } = req.query;

    if (!userId) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户未登录'
      });
    }

    // 构建查询条件
    const where = { userId };
    if (type) where.type = type;
    if (status) where.status = status;

    // 查询反馈列表
    // const feedbacks = await Feedback.findAndCountAll({
    //   where,
    //   limit: parseInt(limit),
    //   offset: (parseInt(page) - 1) * parseInt(limit),
    //   order: [['createdAt', 'DESC']]
    // });

    // 模拟数据
    const feedbacks = {
      count: 0,
      rows: []
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        list: feedbacks.rows,
        total: feedbacks.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });

  } catch (error) {
    logger.error('Failed to get user feedbacks:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取反馈列表失败'
    });
  }
});

// 获取反馈详情
router.get('/:id', async (req, res) => {
  try {
    const userId = req.user?.id;
    const { id } = req.params;

    if (!userId) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户未登录'
      });
    }

    // 查询反馈详情
    // const feedback = await Feedback.findOne({
    //   where: { id, userId }
    // });

    // if (!feedback) {
    //   return res.status(404).json({
    //     success: false,
    //     code: 404,
    //     message: '反馈不存在'
    //   });
    // }

    // 模拟数据
    const feedback = null;

    if (!feedback) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '反馈不存在'
      });
    }

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: feedback
    });

  } catch (error) {
    logger.error('Failed to get feedback detail:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取反馈详情失败'
    });
  }
});

// 管理员获取反馈列表
router.get('/admin/list', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { 
      page = 1, 
      limit = 20, 
      type, 
      status, 
      isGrayUser,
      startDate,
      endDate 
    } = req.query;

    // 构建查询条件
    const where = {};
    if (type) where.type = type;
    if (status) where.status = status;
    if (isGrayUser !== undefined) where.isGrayUser = isGrayUser === 'true';
    if (startDate && endDate) {
      where.createdAt = {
        $between: [new Date(startDate), new Date(endDate)]
      };
    }

    // 查询反馈列表
    // const feedbacks = await Feedback.findAndCountAll({
    //   where,
    //   include: [{ model: User, attributes: ['id', 'nickname', 'phone'] }],
    //   limit: parseInt(limit),
    //   offset: (parseInt(page) - 1) * parseInt(limit),
    //   order: [['createdAt', 'DESC']]
    // });

    // 模拟数据
    const feedbacks = {
      count: 0,
      rows: []
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        list: feedbacks.rows,
        total: feedbacks.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });

  } catch (error) {
    logger.error('Failed to get admin feedbacks:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取反馈列表失败'
    });
  }
});

// 管理员处理反馈
router.put('/admin/:id', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { id } = req.params;
    const { status, reply, priority } = req.body;

    // 查询反馈
    // const feedback = await Feedback.findByPk(id);
    // if (!feedback) {
    //   return res.status(404).json({
    //     success: false,
    //     code: 404,
    //     message: '反馈不存在'
    //   });
    // }

    // 更新反馈状态
    // await feedback.update({
    //   status,
    //   reply,
    //   priority,
    //   processedBy: req.user.id,
    //   processedAt: new Date()
    // });

    logger.info('Feedback processed', { 
      feedbackId: id, 
      status, 
      processedBy: req.user.id 
    });

    res.json({
      success: true,
      code: 200,
      message: '处理成功'
    });

  } catch (error) {
    logger.error('Failed to process feedback:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '处理反馈失败'
    });
  }
});

// 获取反馈统计
router.get('/admin/stats', async (req, res) => {
  try {
    // 检查管理员权限
    if (!req.user?.isAdmin) {
      return res.status(403).json({
        success: false,
        code: 403,
        message: '权限不足'
      });
    }

    const { startDate, endDate } = req.query;
    const dateRange = {};
    
    if (startDate && endDate) {
      dateRange.createdAt = {
        $between: [new Date(startDate), new Date(endDate)]
      };
    }

    // 统计各类型反馈数量
    // const typeStats = await Feedback.findAll({
    //   where: dateRange,
    //   attributes: [
    //     'type',
    //     [sequelize.fn('COUNT', sequelize.col('id')), 'count']
    //   ],
    //   group: ['type']
    // });

    // 统计灰度用户反馈
    // const grayUserStats = await Feedback.findAll({
    //   where: { ...dateRange, isGrayUser: true },
    //   attributes: [
    //     'type',
    //     [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
    //     [sequelize.fn('AVG', sequelize.col('rating')), 'avgRating']
    //   ],
    //   group: ['type']
    // });

    // 模拟统计数据
    const stats = {
      total: 0,
      byType: {},
      byStatus: {},
      grayUserFeedback: {
        total: 0,
        avgRating: 0,
        byType: {}
      },
      trends: []
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: stats
    });

  } catch (error) {
    logger.error('Failed to get feedback stats:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取统计数据失败'
    });
  }
});

// 通知管理员
async function notifyAdmins(feedbackData) {
  try {
    // 发送邮件通知
    // await sendEmail({
    //   to: 'admin@example.com',
    //   subject: `新的${feedbackData.type}反馈`,
    //   html: `
    //     <h3>用户反馈</h3>
    //     <p><strong>类型:</strong> ${feedbackData.type}</p>
    //     <p><strong>标题:</strong> ${feedbackData.title}</p>
    //     <p><strong>内容:</strong> ${feedbackData.content}</p>
    //     <p><strong>用户ID:</strong> ${feedbackData.userId}</p>
    //     <p><strong>是否灰度用户:</strong> ${feedbackData.isGrayUser ? '是' : '否'}</p>
    //   `
    // });

    logger.info('Admin notification sent for feedback', { 
      userId: feedbackData.userId, 
      type: feedbackData.type 
    });
  } catch (error) {
    logger.error('Failed to notify admins:', error);
  }
}

module.exports = router;